package dormouse.vfs.ui.renderers;

import java.awt.BorderLayout;
import java.awt.Component;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;

/**
 * This class is responsible for rendering HTML.
 * 
 * @author Mark
 * 
 */
public class HTMLRenderer extends JPanel implements IFileRenderer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2734952697158042120L;

	private JScrollPane jScrollPane = null;

	private JEditorPane jEditorPane = null;

	private String contentType;
	private static final String ENDL = System.getProperty("line.ending");
        
        private static final String[] EXTS = {"html","htm", "txt", "xml"};

	/**
	 * This method initializes
	 * 
	 */
	public HTMLRenderer() {
		super();
		initialize();
	}
	
	public HTMLRenderer(String contentType){
		this();
		this.contentType = contentType;
	}

	/**
	 * This method initializes this
	 * 
	 */
	private void initialize() {
		this.setLayout(new BorderLayout());
		this.setSize(new java.awt.Dimension(429, 257));
		this.add(getJScrollPane(), java.awt.BorderLayout.CENTER);

	}

	public void render(FileObject file) {
		StringBuffer sb = new StringBuffer();
		try {
			
			BufferedReader in = new BufferedReader(new InputStreamReader(file.getContent().getInputStream()));
			
			String str;
			
			while ((str = in.readLine()) != null) {
				sb.append(str + ENDL);
			}

			in.close();

		} catch (IOException e) {

			e.printStackTrace();

		}
		
		
		
		String contentType = null;
		try {
			contentType = file.getContent().getContentInfo().getContentType();
		} catch (FileSystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (contentType != null){
			this.jEditorPane.setContentType(contentType);
		}
		this.jEditorPane.setText(sb.toString());
	}

	/**
	 * This method initializes jScrollPane
	 * 
	 * @return javax.swing.JScrollPane
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJEditorPane());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes jEditorPane
	 * 
	 * @return javax.swing.JEditorPane
	 */
	private JEditorPane getJEditorPane() {
		if (jEditorPane == null) {
			jEditorPane = new JEditorPane();
		}
		return jEditorPane;
	}

    public String[] getFileExtensions() {
        return EXTS;
    }

    public Component getComponent() {
        return this;
    }
} // @jve:decl-index=0:visual-constraint="10,10"
